<template>
  <div class="create-character-container">
    <el-card class="create-character-card" shadow="always">
      <template #header>
        <div class="header">
          <h2>创建角色</h2>
          <el-button type="primary" plain size="small" @click="handleCancel">返回</el-button>
        </div>
      </template>

      <el-form :model="form" label-width="100px" label-position="top">
        <!-- 头像上传区域 -->
        <div class="avatar-section">
          <div class="avatar-container">
            <el-avatar 
              :size="120" 
              :src="avatarPreview" 
              :icon="UserFilled"
              class="avatar"
            />
            <div class="avatar-actions">
              <el-button 
                type="primary" 
                size="small" 
                @click="$refs.fileInput.click()"
                :loading="loading"
              >
                选择头像
              </el-button>
              <input
                ref="fileInput"
                type="file"
                accept="image/jpeg,image/jpg,image/png,image/webp"
                @change="handleFileSelect"
                style="display: none"
              />
            </div>
            <p class="upload-tip">支持 JPG、PNG、WEBP 格式，文件大小不超过 2MB</p>
          </div>
        </div>

        <!-- 基本信息 -->
        <el-form-item label="角色名称" required>
          <el-input
            v-model="form.name"
            placeholder="请输入角色名称"
            :disabled="loading"
          />
        </el-form-item>

        <el-form-item label="外观描述" required>
          <el-input
            v-model="form.appearance"
            type="textarea"
            :rows="3"
            placeholder="请描述角色的外观特征"
            :disabled="loading"
          />
        </el-form-item>

        <el-form-item label="背景故事" required>
          <el-input
            v-model="form.background"
            type="textarea"
            :rows="4"
            placeholder="请描述角色的背景故事"
            :disabled="loading"
          />
        </el-form-item>

        <el-form-item label="性格特点" required>
          <el-input
            v-model="form.personality"
            type="textarea"
            :rows="3"
            placeholder="请描述角色的性格特点"
            :disabled="loading"
          />
        </el-form-item>

        <el-form-item label="经典台词" required>
          <el-input
            v-model="form.classicLines"
            type="textarea"
            :rows="3"
            placeholder="请输入角色的经典台词"
            :disabled="loading"
          />
        </el-form-item>

        <!-- 错误信息 -->
        <el-alert
          v-if="error"
          :title="error"
          type="error"
          :closable="false"
          style="margin-bottom: 20px;"
        />

        <!-- 操作按钮 -->
        <div class="form-actions">
          <el-button @click="handleCancel" :disabled="loading" size="large">
            取消
          </el-button>
          <el-button 
            type="primary" 
            @click="handleSubmit" 
            :disabled="loading || !isFormValid" 
            :loading="loading"
            size="large"
          >
            {{ loading ? '创建中...' : '创建角色' }}
          </el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { UserFilled } from '@element-plus/icons-vue'
import { useUserStore } from '../stores/user'
import { characterApi } from '../api/character'
import type { CharacterCreateRequest } from '../api/character'

const router = useRouter()
const userStore = useUserStore()

const loading = ref(false)
const error = ref('')
const avatarFile = ref<File | null>(null)
const avatarPreview = ref('')

const form = reactive({
  name: '',
  appearance: '',
  background: '',
  personality: '',
  classicLines: ''
})

// 表单验证
const isFormValid = computed(() => {
  return form.name.trim() && 
         form.appearance.trim() && 
         form.background.trim() && 
         form.personality.trim() && 
         form.classicLines.trim()
})

// 文件选择处理
const handleFileSelect = (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  
  if (!file) return
  
  // 验证文件类型
  const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp']
  if (!allowedTypes.includes(file.type)) {
    error.value = '请选择 JPG、PNG 或 WEBP 格式的图片'
    return
  }
  
  // 验证文件大小 (2MB)
  if (file.size > 2 * 1024 * 1024) {
    error.value = '图片大小不能超过 2MB'
    return
  }
  
  avatarFile.value = file
  error.value = ''
  
  // 预览图片
  const reader = new FileReader()
  reader.onload = (e) => {
    avatarPreview.value = e.target?.result as string
  }
  reader.readAsDataURL(file)
}

// 提交表单
const handleSubmit = async () => {
  if (!isFormValid.value) return
  
  loading.value = true
  error.value = ''
  
  try {
    // 准备创建角色的数据
    const createData: CharacterCreateRequest = {
      name: form.name.trim(),
      appearance: form.appearance.trim(),
      background: form.background.trim(),
      personality: form.personality.trim(),
      classicLines: form.classicLines.trim()
      // 移除userId字段，后端会自动处理
      // 移除image字段，使用头像上传接口处理
    }
    
    // 创建角色
    const createResponse = await characterApi.create(createData)
    console.log('角色创建完整响应:', JSON.stringify(createResponse, null, 2))
    console.log('响应code:', createResponse.code)
    console.log('响应msg:', createResponse.msg)
    console.log('响应data:', createResponse.data)
    console.log('响应data类型:', typeof createResponse.data)
    
    if (createResponse.code === 1) {
      console.log('角色创建成功，检查头像上传条件:')
      console.log('- 是否有头像文件:', !!avatarFile.value)
      console.log('- 响应数据:', createResponse.data)
      
      // 如果有头像文件，上传头像
      if (avatarFile.value) {
        const characterId = createResponse.data
        if (!characterId) {
          console.log('后端未返回角色ID，无法上传头像')
          error.value = '角色创建成功，但后端未返回角色ID，无法上传头像。请联系后端开发人员修改接口返回角色ID。'
          return
        }
        
        try {
          console.log('开始上传头像，角色ID:', characterId)
          const uploadResponse = await characterApi.uploadAvatar(avatarFile.value, characterId)
          console.log('头像上传响应:', uploadResponse)
          
          if (uploadResponse.code === 1) {
            console.log('头像上传成功')
            // 头像上传成功后跳转
            router.push('/app/my-characters')
          } else {
            console.warn('头像上传失败:', uploadResponse.msg)
            error.value = `角色创建成功，但头像上传失败: ${uploadResponse.msg}`
          }
        } catch (uploadError: any) {
          console.error('头像上传异常:', uploadError)
          error.value = `角色创建成功，但头像上传异常: ${uploadError.message}`
        }
      } else {
        // 没有头像文件，直接跳转
        console.log('无头像文件，直接跳转我的角色页面')
        router.push('/app/my-characters')
      }
    } else {
      error.value = createResponse.msg || '创建角色失败'
    }
  } catch (err: any) {
    console.error('创建角色错误:', err)
    error.value = err.response?.data?.msg || err.message || '创建角色失败，请稍后重试'
  } finally {
    loading.value = false
  }
}

// 取消操作
const handleCancel = () => {
  router.push('/app/my-characters')
}
</script>

<style scoped>
.create-character-container {
  padding: 16px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.create-character-card {
  max-width: 800px;
  margin: 0 auto;
}

.avatar-section {
  margin-bottom: 24px;
  padding: 20px;
  text-align: center;
  background: #fafafa;
  border-radius: 8px;
}

.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}

.avatar {
  border: 3px solid #e4e7ed;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.avatar-actions {
  display: flex;
  gap: 8px;
}

.upload-tip {
  font-size: 12px;
  color: #999;
  margin: 0;
}

.form-actions {
  display: flex;
  gap: 16px;
  justify-content: center;
  margin-top: 24px;
}
</style>